<?php

class welcome extends CI_Controller {

  public function __construct() {
    parent::__construct();
  }

  public function index() {
    if (userdata('end_user_user_id') || userdata('subcrised')) {
      redirect('welcome/location');
      return;
    }
    $error = '';
    if (isset($_POST['email'])) {
      if (empty($_POST['email'])) {
        $error = 'Enter your email';
      } else {
        $this->load->helper('email');
        if (!valid_email($_POST['email'])) {
          $error = 'Email is not available';
        } else {
          $subscribe = $this->db->get_where('subscribe', array('email' => $_POST['email']), 1, 0)->result_array();
          if (empty($subscribe)) {
            $this->db->insert('subscribe', array('email' => $_POST['email']));
          }
          set_userdata('subcrised', TRUE);
          redirect('welcome/location');
          return;
        }
      }
    }
    $this->load->view('welcome/index', array('error' => $error));
  }

  public function location() {
    if (!userdata('end_user_user_id') && !userdata('subcrised')) {
      redirect('welcome');
      return;
    }
    $error_country = 0;
    $error_state = 0;
    $error_city = 0;
    $country = 0;
    $city = 0;
    $state = 0;
    if (isset($_POST['country_id'])) {
      if (empty($_POST['country_id'])) {
        $error_country = 1;
      } else
        $country = $_POST['country_id'];
    }
    if (isset($_POST['state_id'])) {
      if (empty($_POST['state_id'])) {
        $error_state = 1;
      } else
        $state = $_POST['state_id'];
    }
    if (isset($_POST['city_id'])) {
      if (empty($_POST['city_id'])) {
        $error_city = 1;
      } else
        $city = $_POST['city_id'];
    }
    if ($country + $state + $city != 0) {
      set_userdata('country_id', $country);
      set_userdata('state_id', $state);
      set_userdata('city_id', $city);
      if (userdata('end_user_current_url'))
        redirect(userdata('end_user_current_url'));
      else
        redirect('index');
      return;
    }
    $this->load->view('welcome/location', array('error_country' => $error_country,
        'error_state' => $error_state, 'error_city' => $error_city,
        'country_id' => $country, 'state_id' => $state, 'city_id' => $city));
  }

}